package org.duang.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpHeaders;
import org.duang.common.dto.HeadDto;
import org.duang.common.dto.ReturnDto;
import org.duang.common.exceptios.ServiceException;
import org.duang.config.Config;
import org.duang.core.Reporter;
import org.duang.core.Reporter.ActionInfo;
import org.duang.http.util.HttpUtil;
import org.duang.kit.ToolsKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@WebServlet(name = "reporter", urlPatterns = { "/reporterservlet" }, loadOnStartup = 2)
public class ReporterServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static Logger logger = LoggerFactory.getLogger(ReporterServlet.class);
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String authStr = request.getHeader(HttpHeaders.AUTHORIZATION);
		if(ToolsKit.isEmpty(authStr)) throw new ServiceException("authStr is empty!");
		if(!HttpUtil.isDuangAuthorizAtionSignKey(authStr)){
			logger.warn("the request is not duang  security request:  " + request.getRequestURL() );
			throw new ServiceException("the request is not duang  security request");
		}
		response.setContentType("text/html;charset=" + Config.getEncoding());
		PrintWriter out = response.getWriter();
		ReturnDto<List<ActionInfo>> dto = new ReturnDto<List<ActionInfo>>();
		HeadDto head = new HeadDto();
		try {
			dto.setData(Reporter.getAllAction());
			head.setMsg("ok");
			head.setRet(0);
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
			head.setMsg(e.getMessage());
			head.setRet(-1);
		}
		dto.setHead(head);
		out.println(ToolsKit.toJsonString(dto));
		out.flush();
		out.close();
	}
}
